/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ModbusRegistersPanel.java
 *
 * Created on 11 janv. 2009, 15:26:06
 */

package modbuspal.slave;

import java.util.logging.Level;
import java.util.logging.Logger;
import modbuspal.automation.Automation;
import modbuspal.binding.Binding;
import modbuspal.binding.BindingEditor;
import modbuspal.toolkit.GUITools;
import modbuspal.main.ModbusConst;

/**
 *
 * @author nnovic
 */
class ModbusRegistersPanel
extends javax.swing.JPanel
implements ModbusConst
{
    private ModbusSlaveDialog slaveDialog;
    private ModbusRegisters registers;
    //private ModbusSlave modbusSlave;

    /** Creates new form ModbusRegistersPanel */
    public ModbusRegistersPanel(ModbusSlaveDialog parent, ModbusRegisters regs)
    {
        slaveDialog = parent;
        registers = regs;
        //modbusSlave = parent.getModbusSlave();
        initComponents();
        registersTable.setTransferHandler( new ModbusRegistersTransferHandler() );
    }


    protected String getCaption_register()
    {
        return "register";
    }

    protected String getCaption_registers()
    {
        return "registers";
    }

    /*
    private int getTranslatedAddressAt(int selectedRow)
    {
        int address = (Integer)registersTable.getValueAt(selectedRow, ModbusRegisters.ADDRESS_COLUMN_INDEX);
        switch(modbusSlave.getImplementation())
        {
            default:
            case IMPLEMENTATION_MODBUS:
                return address-1;
            case IMPLEMENTATION_JBUS:
                return address;
        }
    }
*/
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        addRegistersButton = new javax.swing.JButton();
        removeRegistersButton = new javax.swing.JButton();
        bindRegistersButton = new javax.swing.JButton();
        unbindRegistersButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        registersTable = new ModbusRegistersTable(registers);

        setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        addRegistersButton.setText("Add");
        addRegistersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addRegistersButtonActionPerformed(evt);
            }
        });
        jPanel2.add(addRegistersButton);

        removeRegistersButton.setText("Remove");
        removeRegistersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeRegistersButtonActionPerformed(evt);
            }
        });
        jPanel2.add(removeRegistersButton);

        bindRegistersButton.setText("Bind");
        bindRegistersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bindRegistersButtonActionPerformed(evt);
            }
        });
        jPanel2.add(bindRegistersButton);

        unbindRegistersButton.setText("Unbind");
        unbindRegistersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                unbindRegistersButtonActionPerformed(evt);
            }
        });
        jPanel2.add(unbindRegistersButton);

        add(jPanel2, java.awt.BorderLayout.NORTH);

        registersTable.setAutoCreateRowSorter(true);
        registersTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(registersTable);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void addRegistersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRegistersButtonActionPerformed

        // create and display dialog
        AddRegistersDialog dialog = new AddRegistersDialog( GUITools.findFrame(this), slaveDialog);
        dialog.setTitle("Add "+getCaption_registers());
        slaveDialog.setStatus("Adding "+getCaption_register()+"...");
        dialog.setVisible(true);

        if( dialog.isAdded() == true )
        {
            int start = dialog.getStartingAddress();
            int q = dialog.getQuantity();
            registers.create(start, q);
            slaveDialog.setStatus("Adding "+getCaption_registers()+" completed.");
        } 
        else
        {
            slaveDialog.setStatus("Adding "+getCaption_registers()+" cancelled by user.");
        }
}//GEN-LAST:event_addRegistersButtonActionPerformed

    private void bindRegistersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bindRegistersButtonActionPerformed

        // check the validty of current selection:
        int rowCount = registersTable.getSelectedRowCount();
        
        if( rowCount <= 0 )
        {
            return;
        }

        else
        {
            // display the bind dialog
            BindingEditor dialog = new BindingEditor(slaveDialog.modbusPalPane);
            slaveDialog.setStatus("Binding...");
            dialog.setVisible(true);

            // retrieve the selected automation
            Automation source = dialog.getSelectedAutomation();
            if( source == null )
            {
                slaveDialog.setStatus("Binding cancelled by user.");
                return;
            }

            // get the selected binding order
            int selectedOrder = dialog.getSelectedOrder();
            
            // get the selected binding class
            String selectedClass = dialog.getSelectedClass();

            // get the selected rows
            int selectedAddresses[] = ((ModbusRegistersTable)registersTable).getSelectedAddresses();

            // bind all selected registers
            for(int i=0;i<selectedAddresses.length;i++)
            {
                try
                {
                    // instanciate the binding:
                    Binding binding = slaveDialog.modbusPalProject.getBindingFactory().newInstance(selectedClass);
                    //Binding binding = BindingFactory.newBinding(selectedClass);
                    binding.setup(source, selectedOrder);
                    // do the binding:
                    registers.bind(selectedAddresses[i],binding);
                } 
                catch(Exception ex)
                {
                    Logger.getLogger(ModbusSlaveDialog.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            slaveDialog.setStatus("Binding completed.");
        }
}//GEN-LAST:event_bindRegistersButtonActionPerformed

    private void removeRegistersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRegistersButtonActionPerformed

        // get the selected rows
        int addresses[] = ((ModbusRegistersTable)registersTable).getSelectedAddresses();

        if( addresses.length<=0 )
        {
            return;
        }

        // delete registers
        for( int i=0; i<addresses.length; i++ )
        {
            registers.remove(addresses[i]);
        }

        slaveDialog.setStatus("Registers deleted.");
    }//GEN-LAST:event_removeRegistersButtonActionPerformed

    private void unbindRegistersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unbindRegistersButtonActionPerformed

        // get the selected rows
        int addresses[] = ((ModbusRegistersTable)registersTable).getSelectedAddresses();

        if( addresses.length<=0 )
        {
            return;
        }

        // delete bindings
        for( int i=0; i<addresses.length; i++ )
        {
            registers.unbind(addresses[i]);
        }

        slaveDialog.setStatus("Registers unbound.");
        

    }//GEN-LAST:event_unbindRegistersButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addRegistersButton;
    private javax.swing.JButton bindRegistersButton;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable registersTable;
    private javax.swing.JButton removeRegistersButton;
    private javax.swing.JButton unbindRegistersButton;
    // End of variables declaration//GEN-END:variables

}
